using System.Collections;
using JufGame.AI;
using System.Collections.Generic;
using UnityEngine;

namespace JufGame
{
	public class MyOctreeAStar : MonoBehaviour
	{
		public MyOctreeBuilder octree; //八叉树构建器
		private AStar_Searcher<MyGraph<MyOctreeNode, int>, MyOctreeNode> astar; //A星搜索器
		private Stack<MyOctreeNode> path; //存储路径的栈
		[SerializeField] private Transform start; //寻路起点
		[SerializeField] private Transform end; //寻路终点
		//当该值位false时会进行一次寻路，寻路完成后自动为true
		[SerializeField] private bool isFindPathEnd; 
		private void Start()
		{
			astar = new AStar_Searcher<MyGraph<MyOctreeNode, int>, MyOctreeNode>(octree.Octree.NavGraph);
			path = new Stack<MyOctreeNode>();
		}
		private void Update()
		{
			if(!isFindPathEnd)
			{
				//将起点与终点的位置转化为树中节点，然后进行寻路
				var s = octree.Octree.GetNodeByPos(octree.Octree.RootNode, start.position);
				var e = octree.Octree.GetNodeByPos(octree.Octree.RootNode, end.position);
				astar.FindPath(s, e, path);
				isFindPathEnd = true;
			}
		}
		private void OnDrawGizmos()
		{
			if(Application.isPlaying)
			{
				var prevPos = start.position;
				foreach(var n in path)
				{
					Gizmos.color = Color.red;
					Gizmos.DrawLine(prevPos, n.NodeCube.center);
					prevPos = n.NodeCube.center;
				}
				Gizmos.DrawLine(prevPos, end.position);
			}
		}
	}
}
